package com.yeping;

import java.util.Arrays;
class ListNode {
      int val;
      ListNode next;
      ListNode(int x) {
          val = x;
          next = null;
     }
    ListNode(int x,ListNode next1) {
        val = x;
        next = next1;
    }

    @Override
    public String toString() {
        return "ListNode{" +
                "val=" + val +
                ", next=" + next +
                '}';
    }
}
public class Test {
    public static void main(String[] args) {
        ListNode node = new ListNode(1,new ListNode(2,new ListNode(3)));
        System.out.println(reverseList(node));
    }

    public static ListNode reverseList(ListNode head) {
        // write code here
        //为空
        if (head == null){
            return null;
        }
        //遍历每个节点，头插法
        ListNode h = new ListNode(0);
        ListNode q = head;//当前插入节点
        ListNode p = head;//保存下一节点
        h.next = null;

        while (p != null){
            q = p;
            //获取到下一节点
            p = q.next;
            //接入已有节点
            q.next = h.next;
            //插入头
            h.next = q;
        }
        return h.next;
    }


}
